package com.qingke.hibernate.oneday.dao;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.query.Query;

import com.qingke.hibernate.oneday.pojo.Course;

public class CourseDao {

	private Session session;

	public CourseDao(Session session) {
		this.session = session;
	}

	public Course getCourseById(int id) {
		return session.get(Course.class, id);
	}

	public List<Course> listCourses() {
		Query<Course> query = session.createQuery("from Course", Course.class);
		return query.getResultList();
	}

	public void insert(Course course) {
		Transaction ts = session.beginTransaction();
		try {
			session.save(course);
			session.flush();
			ts.commit();
		} catch (HibernateException he) {
			he.printStackTrace();
			ts.rollback();
		}
	}

	public void update(Course course) {
		Transaction ts = session.beginTransaction();
		try {
			session.update(course);
			ts.commit();
		} catch (HibernateException he) {
			he.printStackTrace();
			ts.rollback();
		}
	}

	public void delete(Course course) {
		Transaction ts = session.beginTransaction();
		try {
			session.delete(course);
			ts.commit();
		} catch (HibernateException he) {
			he.printStackTrace();
			ts.rollback();
		}
	}
}
